package com.fadadianqi.logistics.inventory.service;

import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.logistics.inventory.dao.StorehouseDAO;
import com.fadadianqi.logistics.inventory.model.Item;
import com.fadadianqi.logistics.inventory.model.Storehouse;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StorehouseService {

    public List<Storehouse> findAll() {
        return storehouseDAO.findAll();
    }

    public Storehouse getStorehouseById(String id) {
        if (ValidatorHelper.isEmpty(id)) {
            return null;
        }
        return storehouseDAO.getById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void save(Storehouse storehouse) throws Exception {
        if (ValidatorHelper.isEmpty(storehouse.getName())) {
            throw new Exception("exception.required.name");
        }
        // 新增库房
        if (ValidatorHelper.isEmpty(storehouse.getId())) {
            storehouse.setId(PrimaryKeyCreator.create());
            storehouse.setTotal(0);
            storehouseDAO.create(storehouse);
        }
        // 更新库房
        else {
            storehouseDAO.update(storehouse);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void del(Storehouse storehouse) throws Exception {
        if (storehouse == null) {
            return;
        }
        // 如果库房还有存活则不能被删除
        else if (storehouse.getTotal() != null && storehouse.getTotal().intValue() > 0) {
            throw new Exception("exception.remove.storehouse.have.goods");
        }
        storehouseDAO.remove(storehouse);
    }

    public void update(Storehouse storehouse) {
        storehouseDAO.update(storehouse);
    }

    /**
     * 统计指定库房的指定商品数量
     *
     * @param goods
     * @param sh
     * @return
     */
    public int countGoods(Goods goods, Storehouse sh) {
        String goodsId = null;
        String storehouseId = null;
        if (goods == null) {
            return 0;
        }
        goodsId = goods.getId();
        if (sh != null) {
            storehouseId = sh.getId();
        }
        int status = Item.STATUS_NORMAL;
        return inventoryService.countByGoodsIdAndStorehouseIdAndStatus(goodsId, storehouseId, status);
    }

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private StorehouseDAO storehouseDAO;
}
